package com.example.demo.dao.impl;

import com.example.demo.dao.UserDao;
import com.example.demo.model.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

@Repository("userDao")
@Transactional(rollbackFor = Exception.class)
public class UserDaoImpl implements UserDao {

	@Autowired
	HibernateTemplate hibernateTemplate;


	@Override
	public void deleteBean(User bean) {
		hibernateTemplate.delete(bean);
	}

	@Override
	public void insertBean(User bean) {
		hibernateTemplate.save(bean);
		
	}

	@Override
	@SuppressWarnings("unchecked")
	public User selectBean(String where) {
		List<User> list = (List<User>) hibernateTemplate.find("from User " +where);
		if(list.size()==0){
			return null;
		}
		return list.get(0);
	}

	@Override
	public int selectBeanCount(String where) {
		long count = (Long)hibernateTemplate.find("select count(*) from User "+where).get(0);
		return (int)count;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<User> selectBeanList(final int start,final int limit,final String where) {
		return (List<User>)hibernateTemplate.executeWithNativeSession(new HibernateCallback() {
			@Override
			public Object doInHibernate(final Session session)throws HibernateException {
				List<User> list = session.createQuery("from User "+where)
				.setFirstResult(start)
				.setMaxResults(limit)
				.list();
				return list;
			}
		});
	}

	@Override
	public void updateBean(User bean) {
		hibernateTemplate.update(bean);
		
	}
	
	
}
